###
# Copyright (c) 2006, Dannii Willis
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

###

import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.schedule as schedule
import supybot.callbacks as callbacks
import gzip, httplib, random, re, urllib2, urlparse
from StringIO import StringIO
from sgmllib import SGMLParser

#	Item list
FtGitemList = (
	('blaster',		'blaster 3 shots'),
	('contract12',		'contract 12 ships'),
	('contract50',		'contract 50 ships'),
	('dynamite',		'dynamite box'),
	('encyclopedia',	'encylopedia vol.1'),
	('engguide',		'engineering guide'),
	('explosives',		'explosives box'),
	('flightguide',	'flight instruction'),
	('fuselagefoam',	'fuselage foam'),
	('gingerbiscuit',	'ginger biscuit'),
	('golddetector',	'gold detector'),
	('healthpotion',	'health potion'),
	('industrypatent',	'industrial patent'),
	('irondetector',	'iron detector'),
	('killerguide',	'killer\'s guide'),
	('kungfubook',		'kung-fu book'),
	('maintenancekit',	'maintenance kit'),
	('mulejuice',		'mule juice'),
	('multixmanure',	'multix manure'),
	('neuronicwhip',	'neuronic whip'),
	('nrgpotion',		'nrg potion'),
	('oldblaster',		'pld blaster'),
	('personalshield',	'personal shield'),
	('plasticblaster',	'plastic blaster'),
	('sabotageguide',	''),
	('sectormap',		'sector map'),
	('seldoncookie',	'seldon cookie'),
	('tindetector',	'tin detector'),
	('wig',			'wig'),
	('x27',			'cruiser x27'),
	('x27contract',	'x27 contract'),
	('x27keys',		'x27 keys'),
	('x27licence',		'x27 licence'),
	('x27paperwork',	'x27 paperwork'),
	('x31',			'cruiser x31'),
	('x31contract',	'x31 contract'),
	('x31keys',		'x31 keys'),
	('x31licence',		'x31 licence'),
	('x31paperwork',	'x31 paperwork'),
	('x32kit',		'x32 cruiser kit'),
	('x32radar',		'x32 radar'),
	('x32tank',		'x32 tank')
	)

#	Deposit message regex pattern
#	Must be passed the inner html of the 'admin' div
#depositPattern = re.compile(''.join("""
#	\A											#	Beginning of inner html
#	<br><font\ color=green>							#	a useless linebreak and some colour formatting
#	(\w+)										#	depositor's name
#	</font>\ :\ <u>Teleportation\ succeeded\ </u>\ :\ 	#	successful transfer!
#	([- \w\'.]+)									#	item type
#	\ to\ <b>										#	more text
#	""", self.registryValue('HolobotAccount')),			#	Holobot's name
#	re.VERBOSE)

#	<font color=green>proto</font> : <u>1 credit donation</u> to <b>reximus</b>

#	URL Handler
class FtGloginRedirectHandler(urllib2.HTTPRedirectHandler):
	def http_error_302(self, req, fp, code, msg, headers):
		if 'location' in headers:
			newurl = headers.getheaders('location')[0]
		elif 'uri' in headers:
			newurl = headers.getheaders('uri')[0]
		else:
			return
		self.newurl = urlparse.urljoin(req.get_full_url(), newurl)

		fp.read()
		fp.close()

		self.status = code
		return self

#	Planet List regex pattern
#	Matches something like '564-476-Empire55905-30'
planetListPattern = re.compile('^\d{3}-\d{3}-\w+-\d{2,3}$')

#	Planet List SGML Parser
class PlanetListParser(SGMLParser):
	def reset(self):
		SGMLParser.reset(self)
		self.planetlist = []

	def start_option(self, attrs):
		planetid = [v for k, v in attrs if k == 'value']
		if planetid:
			self.planetlist.extend(planetid)

class Holobot(callbacks.Plugin):
	"""This plugin controls the Senator bot as it logs into and uses FtG's Holochat system."""
	threaded = True

	def __init__(self, irc):
		self.__parent = super(Holobot, self)
		self.__parent.__init__(irc)
		self.userAgent = 'Senator/0.1 +http://ftgforums.com'
		self.SESSID = ''

#	Function to log into FtG and get a session
	def FtGlogin(self):
		requesturl = 'http://foundationgame.com/chargement.php?login=%s&pwd=%s' % (self.registryValue('HolobotAccount'), self.registryValue('HolobotAccountPass'))
#		irc.reply(requesturl)
		request = urllib2.Request(requesturl)
#		request.add_header('Accept-encoding', 'gzip')
		request.add_header('User-Agent', self.userAgent)
		opener = urllib2.build_opener(FtGloginRedirectHandler())
		page = opener.open(request)
#		irc.reply(page.newurl)
		spliturl = urlparse.urlsplit(page.newurl)
		page.close()
		if spliturl[2] == '/inter_mission.php':
			raise callbacks.Error, 'Account currently not in mission, FtG login aborted'
		sessiondata = spliturl[3].split('=')
		if sessiondata[0] == 'ident':
			self.SESSID = sessiondata[1]
			return 'FtG login successful ' + self.SESSID
		else:
			raise callbacks.Error, 'Incorrect Username/Password combination for FtG login'

#	Function to move a leader in FtG
	def FtGMoveLeader(self, leaderID = None):
		if leaderID == None:
			leaderID = self.registryValue('HolobotLeaderID')
		requesturl = 'http://foundationgame.com/leader.php?ident=%s&id_leader=%s' % (self.SESSID, leaderID)
#		irc.reply(requesturl)
		request = urllib2.Request(requesturl)
		request.add_header('Accept-encoding', 'gzip')
		request.add_header('User-Agent', self.userAgent)
		opener = urllib2.build_opener()
		page = opener.open(request)
		data = page.read()
		page.close()
		if hasattr(page, 'headers'):
			if page.headers.get('content-encoding', '') == 'gzip':
				data = gzip.GzipFile(fileobj=StringIO(data)).read()
#		irc.reply(data)
		if 'Session has expired' in data:
			self.FtGlogin()
			return self.FtGMoveLeader(leaderID)
		elif 'Database error' in data:
			raise callbacks.Error, 'Bad leader ID, leader movement aborted'
		elif 'leaving my home planet' in data or 'will land in' in data or 'jump through hyperspace' in data:
			return 'Leader already in transit'
		elif 'change location' in data:
			parser = PlanetListParser()
			parser.feed(data)
			parser.close()
			parser.planetlist = filter(planetListPattern.search, parser.planetlist)
			destination = random.choice(parser.planetlist)
			requesturlB = 'http://foundationgame.com/leader.php?ident=%s&id_leader=%s&action=1&planete=%s' % (self.SESSID, leaderID, destination)
#			irc.reply(requesturlB)
			requestB = urllib2.Request(requesturlB)
			requestB.add_header('Accept-encoding', 'gzip')
			requestB.add_header('User-Agent', self.userAgent)
			openerB = urllib2.build_opener()
			pageB = openerB.open(requestB)
			pageB.close()
			return 'Leader successfully moved'
		else:
			raise callbacks.Error, 'Unknown leader status, leader movement aborted'

#	Function to log into Holochat
	def HolochatLogin(self, leaderID = None, loginTries = 0):
		if leaderID == None:
			leaderID = self.registryValue('HolobotLeaderID')
		requesturl = 'http://foundationgame.com/holochat/holo_chat.php?ident=%s&id_leader=%s' % (self.SESSID, leaderID)
#		irc.reply(requesturl)
		request = urllib2.Request(requesturl)
		request.add_header('Accept-encoding', 'gzip')
		request.add_header('User-Agent', self.userAgent)
		opener = urllib2.build_opener()
		page = opener.open(request)
		data = page.read()
		page.close()
		if hasattr(page, 'headers'):
			if page.headers.get('content-encoding', '') == 'gzip':
				data = gzip.GzipFile(fileobj=StringIO(data)).read()
#		irc.reply(data)
		if 'Session has expired' in data:
			self.HolochatLogin()
			return self.HolochatLogin(leaderID)
		elif 'Connection to Holo-meeting has failed' in data:
			if loginTries == 0:
				return self.HolochatLogin(leaderID, 1)
			else:
				raise callbacks.Error, 'Holochat login aborted: leader in transit/bad leader ID'
		elif 'intro_chat.html' in data:
			return 'Holochat login successful'
		else:
			raise callbacks.Error, 'Unknown Holochat status'
			
	def HolochatLogout(self)
		requesturl = 'http://foundationgame.com/holochat/quitchat.php?pseudo=%s' % (self.registryValue('HolobotAccount'), )
#		irc.reply(requesturl)
		request = urllib2.Request(requesturl)
		request.add_header('Accept-encoding', 'gzip')
		request.add_header('User-Agent', self.userAgent)
		opener = urllib2.build_opener()
		page = opener.open(request)
		page.close()
		return 'Holochat logout successful'

	def holologin(self, irc, msg, args):
		"""Logs Senator into Holochat."""
		irc.reply(self.FtGlogin())
#		irc.reply(self.HolochatLogin())
#		irc.reply(self.FtGMoveLeader())
		try:
			schedule.addPeriodicEvent(self.FtGMoveLeader, 15600, 'FtGMoveLeader', False)
		except AssertionError:
			irc.reply('Future movements already scheduled')
		else:
			irc.reply('Future movements scheduled')
		irc.reply('Senator has been logged into Holochat')
	holologin = wrap(holologin)

	def holologout(self, irc, msg, args):
		"""Logs Senator out of Holochat."""
		irc.reply(self.HolochatLogout())
		irc.reply('Leader movements unscheduled')
		schedule.removeEvent('FtGMoveLeader')
		irc.reply('Senator has been logged out of Holochat')
	holologout = wrap(holologout)

Class = Holobot
